<template>
  <div class="comment">
    <h4>发表评论</h4>
    <hr />
    <textarea placeholder="请输入需要评论的内容(最多输入80个字)" maxlength="80" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>
    <div v-for="(item,index) in comments" :key="index">
      <p class="ctitle">第{{index}}楼 用户:{{item.user_name}} 发表时间：{{item.add_time | dateFormat }}</p>
      <div class="ccontent">{{item.content !== 'undefined' ? item.content : '该用户没有输入任何评论'}}</div>
    </div>
    <mt-button type="danger" size="large" plain @click="getMoreComment">加载更多</mt-button>
  </div>
</template>

<script>
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      comments: [],
      pageIndex: 1, //默认页面为1
      msg: ""
    };
  },
  props: ["artid"],
  created() {
    this.getComment();
  },
  methods: {
    getComment() {
      this.$http
        .get(
          "http://www.liulongbin.top:3005/api/getcomments/" +
            this.artid +
            "?pageindex=" +
            this.pageIndex
        )
        .then(res => {
          if (res.data.status == 0) {
            //     拼接评论数据，而不是覆盖评论数组
            res.data.message.length ? res.data.message : Toast("没有更多数据");
            this.comments = this.comments.concat(res.data.message);
            // console.log(res.data.message);
          }
        })
        .catch(function(error) {
          // handle error
          Toast("获取评论列表失败");
        });
    },
    getMoreComment() {
      this.pageIndex++;
      this.getComment();
    },
    postComment() {
      this.$http
        .post("http://www.liulongbin.top:3005/api/postcomment/" + this.artid)
        .then(res => {
          if (res.data.status === 1) {
            Toast(res.data.message);
          }
        })
        .catch(function(error) {
          // handle error
          Toast("提交失败");
        });
    }
  }
};
</script>

<style lang="less" scoped>
.comment {
  h4 {
    font-size: 15px;
  }
  textarea {
    margin-bottom: 0;
    font-size: 14px;
  }
  button {
    margin-bottom: 10px;
  }
  .ctitle {
    background-color: #ccc;
  }
  .ccontent {
    background-color: #fff;
    font-size: 14px;
  }
}
</style>